﻿<%@ Assembly Name="Microsoft.SharePoint.ApplicationPages, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBar" src="~/_controltemplates/ToolBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBarButton" src="~/_controltemplates/ToolBarButton.ascx" %>
<%@ Register TagPrefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="wssap" Namespace="Microsoft.SharePoint.ApplicationPages"
    Assembly="Microsoft.SharePoint.ApplicationPages, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace= "Microsoft.SharePoint.ApplicationPages" %>
<%@ Import Namespace= "System.Data" %>
<%@ Import Namespace= "System.IO" %>
<%@ Import Namespace= "System.Xml" %>
<%@ Import Namespace= "System.Xml.Serialization" %>
<%-- 
   // Forms Based Authentication User and Role Management - Attribution notice
   // Author(s):
   //
   //      Edin Kapic (ekapic@gmail.com, http://edinkapic.blogspot.com)
   //
   // This file is distributed under the terms of the Microsoft Community 
   // License (Ms-CL). See http://www.codeplex.com/features/Project/License.aspx
   // for the complete terms of use. 
   //
   // For any distribution that contains code from this file, this notice of 
   // attribution must remain intact, and a copy of the license must be 
   // provided to the recipient.
--%>
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    <SharePoint:EncodedLiteral ID="PageTitle"
						Text="Import Forms Based Authentication Users"
						EncodeMethod="HtmlEncode" runat="server"/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    <SharePoint:EncodedLiteral ID="TitleArea"
						Text="Import Forms Based Authentication Users"
						EncodeMethod="HtmlEncode" runat="server"/>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PlaceHolderPageDescription" runat="server">
    Use this page to import forms based authentication users into SharePoint groups. To import users into the a group, choose the appropiate group from the toolbar, select the users you wish to import and click Import Selected Users button.
	  <wssuc:ToolBar id="onetidNavNodesTB" runat="server">
		<Template_Buttons>
		  <wssuc:ToolBarButton runat="server"
						Text="Import Selected Users"
						id="idImportUsers"
						ToolTip="New Role"
						OnClick="ImportUsersEventHandler" 
						ImageUrl="/_layouts/images/newitem.gif"
						AccessKey="I"/>		    
		</Template_Buttons>
		
<%--	
        This has been removed to avoid confusion.  Typically a site will only have one provider.
        This user control allows you to manage more than one provider.
--%>        
        <Template_RightButtons>
            <wssawc:EncodedLiteral runat="server" Text="Choose the group to import to: "></wssawc:EncodedLiteral>
		    <asp:DropDownList id="ddlGroups" runat="server"  AutoPostBack="false"  />
		</Template_RightButtons>  
	  </wssuc:ToolBar>

</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <table border="0" cellpadding="10" cellspacing="10">
        <tr>
            <td>
            <h3 class="ms-standardheader"><SharePoint:EncodedLiteral ID="HeaderText" runat="server" text="Users" EncodeMethod='HtmlEncode'/> &nbsp;</h3>
            <wssawc:MenuTemplate ID="UserMenu" runat="server">
                <wssawc:MenuItemTemplate ID="Details" runat="server" Text="Edit" ImageUrl="/_layouts/images/EDITITEM.GIF" ClientOnClickNavigateUrl="UserEdit.aspx?UserName=%USERNAME%" Title="Edit"></wssawc:MenuItemTemplate>
                <wssawc:MenuItemTemplate ID="Delete" runat="server" Text="Delete" ImageUrl="/_layouts/images/delete.gif" ClientOnClickNavigateUrl="UserDelete.aspx?UserName=%USERNAME%" Title="Delete"></wssawc:MenuItemTemplate>
            </wssawc:MenuTemplate>
                <wssawc:SPGridView ID="MemberGrid" DataKeyNames="UserName" AutoGenerateColumns="false"
                    CssClass="ms-vb2" GridLines="None" HeaderStyle-HorizontalAlign="Left" runat="server"  
                    AllowPaging="true" PagerStyle-CssClass="ms-bottompaging" PagerStyle-HorizontalAlign="Center"
                    PageSize="5" PagerSettings-Mode="NextPreviousFirstLast" >

                    <Columns>
                         <asp:TemplateField HeaderText="Select">
                            <ItemTemplate>
                                <asp:CheckBox ID="chkSelect" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>                       
                        <wssawc:SPMenuField  
                            HeaderText="Username" 
                            TextFields="UserName"
                            MenuTemplateId="UserMenu"
                            NavigateUrlFields="UserName" 
                            NavigateUrlFormat="UserEdit.aspx?UserName={0}" 
                            TokenNameAndValueFields="USERNAME=UserName"
                            SortExpression="UserName" CheckedMenuItemIdsFields="" DisabledMenuItemIdsFields="" HiddenMenuItemIdsFields="" ImageUrlFields="" ImageUrlFormat="" MenuFormat="ArrowOnHover" MenuTemplateIdField="" TextCssClass="" TextFormat="" ToolTipFields="" ToolTipFormat="" UseMaximumWidth="True" 
                             />
                        <wssawc:SPBoundField DataField="Email" HeaderText="E-mail" >
                            <HeaderStyle Width="200px" />
                        </wssawc:SPBoundField>
                        <wssawc:SPBoundField DataField="CreationDate" HeaderText="Creation Date" >
                            <HeaderStyle Width="200px" />
                        </wssawc:SPBoundField>
                    </Columns>
                    <HeaderStyle HorizontalAlign="Left" />
                    <AlternatingRowStyle CssClass="ms-alternating" />
                    <PagerSettings Mode="NumericFirstLast" />
                    <SelectedRowStyle CssClass="ms-selectednav" Font-Bold="True" />
                    <PagerStyle CssClass="ms-bottompaging" />
                    
                </wssawc:SPGridView>
                <wssawc:SPGridViewPager GridViewId="MemberGrid" runat="server" OnClickNext="MemberGrid_ClickNext" OnClickPrevious="MemberGrid_ClickPrevious" >
                </wssawc:SPGridViewPager>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblMessage" class="ms-info" ForeColor="Red" Visible="false" runat="server"></asp:Label>
            </td>
        </tr>
    </table>
</asp:Content>



<script runat="server">

    SPSite site;
    SPWeb web;

        
    protected void Page_Load(object sender, EventArgs e)
    {
        //if you want to manage more than one provider uncoment this code and the user control above.
        // this.appNameSelector.SelectionMade += new EventHandler(appNameSelector_SelectionMade);

        site = SPContext.Current.Site;
        web = site.OpenWeb();
        lblMessage.Visible = false;
        
        if (!Page.IsPostBack)
        {
            FillGroups();
            FillGrid();
        }
    }

    protected void ImportUsersEventHandler(Object sender, EventArgs e)
    {
        SPGroup group = web.Groups[ddlGroups.SelectedValue];
        StringBuilder sb = new StringBuilder();
        sb.Append("Successfully added users: ");
        
        foreach (GridViewRow gvr in MemberGrid.Rows)
        {
            CheckBox chkSelect = (CheckBox) gvr.FindControl("chkSelect");
            if (chkSelect.Checked)
            {
                chkSelect.Checked = false;
                
                string username = ((DataKey)MemberGrid.DataKeys[gvr.RowIndex]).Value.ToString();
                MembershipUser mu = Membership.GetUser(username, false);
                username = mu.ProviderName + ":" + mu.UserName;

                SPUser user = null;
                try
                {
                    user = web.AllUsers[username];
                }
                catch
                {
                    // --- The user hasn't entered SharePoint yet
                }
                if (user != null)
                {
                    group.AddUser(user);
                }
                else
                {
                    // --- If user doesn't exists (yet), add the user to the users collection of the site
                    web.SiteUsers.Add(username, mu.Email, mu.UserName, "Imported from MembershipProvider " + mu.ProviderName + " at " + DateTime.Now.ToString());
                    user = web.AllUsers[username];
                    group.AddUser(user);
                }
                sb.Append( "\n" + mu.UserName);
            }
            lblMessage.Text = sb.ToString();
            lblMessage.Visible = true;
        }

    }

    protected void FillGroups()
    {
        
        // --- Get the site groups
        foreach (SPGroup group in web.Groups)
        {
            ddlGroups.Items.Add(group.Name);
        }

    }
    
    protected void MemberGrid_ClickNext(Object sender, EventArgs e)
    {
        FillGrid();
    }

    protected void MemberGrid_ClickPrevious(Object sender, EventArgs e)
    {
        FillGrid();
    }
        
    protected void appNameSelector_SelectionMade(object sender, EventArgs e)
    {
        FillGrid();
    }
    
    protected void FillGrid()
    {
        MembershipUserCollection users = new MembershipUserCollection();
        if (ddlGroups.Items.Count > 0)
        {
            string rolename = Request.QueryString["Role"] != null ? Request.QueryString["Role"].ToString() : "";
            
            MembershipUser user;
            int totalUsers;

            if (rolename == "")
            {
                users = Membership.GetAllUsers(0, 99999, out totalUsers);
            }
            else
            {
                HeaderText.Text = "Users in '" + rolename + "' role";
                string[] usernames = Roles.GetUsersInRole(rolename);
                for (int i = 0; i < usernames.Length - 1; i++)
                {
                    user = Membership.GetUser(usernames[i], false);
                    if (user != null)
                    {
                        users.Add(user);
                    }
                }
            }

            MemberGrid.DataSource = users;
            MemberGrid.DataBind();
        }
    }
    
    
</script>

